﻿using Api.Application.Command.Menu;
using Api.DTO;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.Menu
{
    public class GetMenuTreeHandler : IRequestHandler<GetMenuTreeCommand, ApiResult<List<TreeMenuDTO>>>
    {
        private readonly IBase<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public GetMenuTreeHandler(IBase<MenuModel> menuRepo, IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<TreeMenuDTO>>> Handle(GetMenuTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<TreeMenuDTO>> result = new ApiResult<List<TreeMenuDTO>>();
            result.Code = ApiEnum.OK;
            result.Msg = "显示树形成功";
            result.Data = GetTree(0);
            return Task.FromResult(result);
        }

        private List<TreeMenuDTO> GetTree(int pid)
        {
            var info = menuRepo.GetAll().Where(x => x.PId == pid && !x.IsDeleted).ToList();
            var model = mapper.Map<List<TreeMenuDTO>>(info);
            foreach (var item in model)
            {
                item.Children = GetTree(item.Id);
            }
            return model;
        }
    }
}
